package com.ukao.steward.ui.main;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;
import com.ukao.steward.R;
import com.ukao.steward.base.BaseActivity;
import com.ukao.steward.base.BaseApplication;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.eventbus.MainEvent;
import com.ukao.steward.eventbus.WorkEvent;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.service.GpsUpdateService;
import com.ukao.steward.ui.menuLeft.SettingActivity;
import com.ukao.steward.ui.menuLeft.myEarnings.MyEarningsFragment;
import com.ukao.steward.ui.menuLeft.personalCenter.PersonalCenterFragment;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.ImageUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.SwitchButton;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import me.yokeyword.fragmentation.SupportFragment;
import rx.Observable;
import sunmi.payservicelib.SunmiPayService;
import woyou.aidlservice.jiuiv5.IWoyouService;

import static me.yokeyword.fragmentation.ISupportFragment.SINGLETASK;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, BaseFragment.OnFragmentOpenDrawerListener{

    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.nav_view)
    NavigationView navigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    private Intent service;
    private boolean islogistics;
    public   static   IWoyouService woyouService;
    private SunmiPayService sunmiPayService;
    private SwitchButton switchBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        initListener();
        JPushInterface.setAlias(getApplicationContext(), Constant.ALIAS_TAG, SaveParams.getAlias());
    }
    @Override
    protected void initView() {
        if (!CheckUtils.isMIUIDevices()){
            Beta.checkUpgrade(false,false);/*不提示正在检查更新，2不弹提示*/
        }

        startGpsUpdateService();
        startMiuiServiceIntent();
        connectPayService();
        SupportFragment fragment = findFragment(HomeFragment.class);
        if (fragment == null) {
            loadRootFragment(R.id.fl_container, HomeFragment.newInstance("",""));
        }
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        toggle.syncState();
        fillData();
    }


    /**
     * 开启定位服务
     */
    private void startGpsUpdateService() {
        service= new Intent(getApplication(),GpsUpdateService.class);
        startService(service);
        bindService(service, conn, Context.BIND_AUTO_CREATE);
    }


    /**
     * 开启小米NFC服务
     */
    private void connectPayService() {
        if (CheckUtils.isMIUIDevices()){
            sunmiPayService= SunmiPayService.getInstance();
            sunmiPayService.connectPayService(getApplicationContext(), connCallback);
        }

    }
    private SunmiPayService.ConnCallback connCallback = new SunmiPayService.ConnCallback() {

        @Override
        public void onServiceConnected() {
            BaseApplication.mHardwareOpt = sunmiPayService.mHardwareOpt;

        }

        @Override
        public void onServiceDisconnected() {

        }

    };


    /**
     * 填充左菜单信息
     */
    private void fillData() {
        LinearLayout llNavHeader = (LinearLayout) navigationView.getHeaderView(0);
        TextView name= (TextView) llNavHeader.findViewById(R.id.product_name);
        TextView   phone= (TextView) llNavHeader.findViewById(R.id.phone);
        TextView   isRest= (TextView) llNavHeader.findViewById(R.id.isRest);
        TextView personnel= (TextView) llNavHeader.findViewById(R.id.personnel);
        ImageView headImage= (ImageView) llNavHeader.findViewById(R.id.head_image);
        LinearLayout headLayout= (LinearLayout) llNavHeader.findViewById(R.id.head_layout);
         switchBtn= (SwitchButton) llNavHeader.findViewById(R.id.switch_btn);
        LinearLayout switchLayout= (LinearLayout) llNavHeader.findViewById(R.id.switch_layout);


        if(SaveParams.getIsRest()){
            switchBtn.openSwitch();
            isRest.setText(R.string.order_in);
        } else{
            isRest.setText(R.string.not_in_service);
            switchBtn.closeSwitch();
        }

        name.setText(SaveParams.getUseName());
        phone.setText(SaveParams.getSaveUsePhone());
        ImageUtils.loadImage(this, SaveParams.getHeadimgPath(), headImage, R.drawable.nav_header_header);
        islogistics= SaveParams.getislogistics();
        if (islogistics){
            switchLayout.setVisibility(View.INVISIBLE);
        }
        personnel.setText(islogistics?getString(R.string.logistics_personnel):getString(R.string.valet_runner));
        navigationView.inflateMenu(islogistics ? R.menu.activity_main_drawers : R.menu.activity_main_drawer);
        headLayout.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            start(PersonalCenterFragment.newInstance("",""), SINGLETASK);

        });


    }



    /**
     * 开启小米打印服务
     */
    private void startMiuiServiceIntent() {
        Intent intent = new Intent();
        intent.setPackage("woyou.aidlservice.jiuiv5");
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        startService(intent);//启动打印服务
        bindService(intent, connService, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection connService = new ServiceConnection() {



        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService= IWoyouService.Stub.asInterface(service);
        }
    };


    public   static  IWoyouService   getPrintService(){


        return woyouService;
    }




    @Override
    protected void initListener() {
        super.initListener();
        navigationView.setNavigationItemSelectedListener(this);
        switchBtn.setOnClickListener(v -> {
            setWorkingState();


        });
    }

    /**
     *  设置开工状态
     */
    public void setWorkingState(  ) {
         showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParams.getToken());
        Observable observable=null;
        if (switchBtn.isSwitchOpen()) {
            observable=apiStores().rest (Constant.createParameter(mHashMap));
        }else{
            observable=apiStores().onLine (Constant.createParameter(mHashMap));
        }
        addSubscription(observable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {

                        if (model.getHttpCode() == 200) {
                            if (switchBtn.isSwitchOpen()) {
                                switchBtn.closeSwitch();
                                SaveParams.saveIsRest(false);

                            }else{
                                switchBtn.openSwitch();
                                SaveParams.saveIsRest(true);
                            }

                            WorkEvent.postNoData(WorkEvent.Message.WOKE_STATE);

                        } else {


                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });

    }


    @Override
    public void onBackPressedSupport() {

        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            int mEntryCount = getSupportFragmentManager().getBackStackEntryCount();
            if(mEntryCount> 1) {
                switch (mEntryCount) {
                    case 2:
                        navigationView.setCheckedItem(R.id.nav_camera);
                        break;
                }
                pop();
            } else {

                if(System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                    finish();
                } else {
                    TOUCH_TIME = System.currentTimeMillis();
                    T.show("再按一次退出");
                }
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
//            Log.d("进来了?", "dispatchTouchEvent: ");
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MainEvent event) {
        switch (event.getMessage()) {
            case START_WORK:  /*打开接单按钮*/
                    switchBtn.openSwitch();
                break;
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.

        switch (item.getItemId()) {
            case R.id.nav_camera: /*控制台*/
                HomeFragment fragment = findFragment(HomeFragment.class);
                start(fragment, SINGLETASK);
                break;
            case R.id.nav_setting: /*设置*/
             ActivityUtils.JumpToActivity(MainActivity.this, SettingActivity.class);
                break;
            case R.id.nav_gallery: /*我的收入*/
                start(MyEarningsFragment.newInstance("", ""), SINGLETASK);
                break;
        }
//       else if (id == R.id.nav_slideshow) {/*我发展的客户*/
//
//        } else if (id == R.id.nav_manage) {/*推广码*/
//
//        }  else if (id == R.id.nav_send) {/*联系客服*/
//
//        }

        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onOpenDrawer() {
        if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    }
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            GpsUpdateService.GPSServiceBinder binder = (GpsUpdateService.GPSServiceBinder) service;

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        unbindService(connService);
            if (sunmiPayService != null) {
                sunmiPayService.unbindPayService(getApplicationContext());
            }
    }
}
